<template>
  <el-form-item v-if="isShow" :class="[inline?'':itemType,compClass]" :label="itemInfo.columnComment"
                :prop="'fieldInfo.'+index+'.fieldData'"
                :rules="itemRule">
    <!--搜索输入框-->
    <el-input v-if="itemInfo.htmlType=='searchInput'" v-model="itemInfo.fieldData" :disabled="isEdit"
              :placeholder="'请输入'+itemInfo.columnComment"
              @change="ItemValChange">
      <el-button slot="append" icon="el-icon-search" @click="openSearch(itemInfo.searchModel)"></el-button>
    </el-input>
    <!-- 计数器 -->
    <el-input-number v-if="itemInfo.htmlType=='inputNumber'" v-model="itemInfo.fieldData"
                     @change="ItemValChange"></el-input-number>
    <!-- 开关 -->
    <el-switch
      v-if="itemInfo.htmlType=='switch'"
      v-model="itemInfo.fieldData"
      :disabled="isEdit"
      @change="ItemValChange"
      active-color="#13ce66"
      inactive-color="#ff4949">
    </el-switch>
    <!-- 滑块 -->
    <el-slider
      v-if="itemInfo.htmlType=='slider'"
      v-model="itemInfo.fieldData"
      :disabled="isEdit"
      @change="ItemValChange"></el-slider>
    <!--输入框-->
    <el-input v-if="itemInfo.htmlType=='input'" v-model="itemInfo.fieldData" v-bind="attributes" @change="ItemValChange"/>

    <!--多行文本-->
    <el-input v-if="itemInfo.htmlType=='textarea'" v-model="itemInfo.fieldData" v-bind="attributes" @change="ItemValChange"/>

    <!--整数类型-->
    <el-input v-if="itemInfo.htmlType=='number'" v-model.number.trim="itemInfo.fieldData" :disabled="isEdit"
              type="number"
              :placeholder="'请输入'+itemInfo.columnComment" @change="ItemValChange"/>
    <!--小数类型-->
    <el-input v-if="itemInfo.htmlType=='decimals' || itemInfo.htmlType=='decimals2'" v-model.trim="itemInfo.fieldData"
              :disabled="isEdit" @keyup.native="itemInfo.fieldData=oninput(itemInfo.fieldData,itemInfo.htmlType)"
              @change="itemInfo.fieldData=oninput(itemInfo.fieldData,itemInfo.htmlType)"
              :placeholder="'请输入'+itemInfo.columnComment"/>
    <!--富文本-->
    <editor v-if="itemInfo.htmlType=='editor'" v-model="itemInfo.fieldData" :disabled="isEdit" :min-height="192"
            @change="ItemValChange"/>
    <!--下拉框-->
    <el-select v-if="itemInfo.htmlType=='select'" v-model="itemInfo.fieldData" :disabled="isEdit"
               :placeholder="'请选择'+itemInfo.columnComment"
               filterable clearable @change="ItemValChange">
      <el-option v-for="(dict,index) in dictList" :key="index" :label="dict.dictLabel" :value="dict.dictValue"
                 :disabled="2==dict.status"/>
    </el-select>
    <!--多选下拉框-->
    <el-select v-if="itemInfo.htmlType=='multipleSelect'" multiple v-model="multipleSelectFieldData" :disabled="isEdit"
               :placeholder="'请选择'+itemInfo.columnComment" filterable clearable @change="ItemValChange"
               :collapse-tags="true">
      <el-option v-for="(dict,index) in dictList" :key="index" :label="dict.dictLabel" :value="dict.dictValue"/>
    </el-select>
    <!--复选框-->
    <el-checkbox-group  v-if="itemInfo.htmlType=='checkbox'" v-model="checkobxFieldData" :disabled="isEdit" @change="ItemValChange">
      <el-checkbox v-for="item in dictList" :label="item.dictValue" :key="item.dictLabel">{{item.dictLabel}}</el-checkbox>
    </el-checkbox-group>
    <!--单选框-->
    <template v-if="itemInfo.htmlType=='radio'">
      <el-radio v-for="item in dictList" v-model="itemInfo.fieldData" :disabled="isEdit"
                      @change="ItemValChange" :label="item.dictValue">{{item.dictLabel}}
      </el-radio>
    </template>
    <!--  日期选择  -->
    <el-date-picker v-if="itemInfo.htmlType=='date'"
                    clearable size="small" style="width: 200px"
                    :disabled="isEdit" v-model="itemInfo.fieldData" type="date" value-format="yyyy-MM-dd"
                    format="yyyy-MM-dd"
                    :placeholder="'选择'+itemInfo.columnComment" @change="ItemValChange">
    </el-date-picker>
    <!--时间选择-->
    <el-date-picker v-if="(itemType=='edit' || itemType == 'add') && itemInfo.htmlType=='datetime'" clearable
                    size="small" style="width: 200px"
                    :disabled="isEdit" v-model="itemInfo.fieldData" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                    format="yyyy-MM-dd HH:mm:ss"
                    :placeholder="'选择'+itemInfo.columnComment" @change="ItemValChange">
    </el-date-picker>
    <el-date-picker v-if="itemType=='query' && itemInfo.htmlType=='datetime'" clearable size="small"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    format="yyyy-MM-dd HH:mm:ss" v-model="itemInfo.fieldData" type="datetimerange" range-separator="-"
                    start-placeholder="开始日期" end-placeholder="结束日期" :placeholder="'选择'+itemInfo.columnComment"
                    @change="ItemValChange" :default-time="['00:00:00','23:59:59']"></el-date-picker>
  </el-form-item>
</template>

<script>

export default {
  name: 'FormItem',
  props: {
    index: {
      type: Number,
      default: 1
    },
    itemType: {
      type: String,
      default: 'edit'
    },
    inline: {
      type: Boolean,
      default: false
    },
    itemInfo: {
      type: Object,
      default: {}
    },
    disableStatus: {
      type: Boolean,
      default: () => {
        return false
      }
    }
  },
  data() {
    return {
      isFullItem: false,
      dictList: []
    }
  },
  created() {
  },
  methods: {
    openSearch(model){
      let searchModel = {
        model: model,
        isOpenSearch: true
      }
      this.$emit('OpenSearchModel', searchModel)
    },
    ItemValChange(val) {
      if (this.itemType == 'query' && (this.itemInfo.htmlType == 'datetime' || this.itemInfo.htmlType == 'date')) {
        if (!this.strIsNotEmpty(this.itemInfo.fieldData)) {
          let dateObj = {
            key: this.itemInfo.columnName,
            type: 'timeParams',
            val: null
          }
          this.$emit('ItemValChange', dateObj)
          return
        }
        if (this.strIsNotEmpty(this.itemInfo.columnName) == true && val) {
          if(this.itemInfo.htmlType == 'date'){
            let dateObj = {
              key: this.itemInfo.columnName,
              type: 'timeParams',
              val: val
            }
            this.$emit('ItemValChange', dateObj)
          }else{
            let dateObj = {
              key: this.itemInfo.columnName,
              type: 'timeParams',
              val: val[0] + ' TO '+ val[1]
            }
            this.$emit('ItemValChange', dateObj)
          }
        }
      } else {
        if (val instanceof Array) {
          val = val.filter(Boolean).join(",")
        }
        if (this.itemInfo.htmlType == 'number') {
          val = Number(val)
        }
        let data = {
          key: this.itemInfo.columnName,
          val: val
        }
        this.$emit('ItemValChange', data)
      }
    },
    oninput(num, htmlType) {
      var str = num + ""
      var len1 = str.substr(0, 1)
      var len2 = str.substr(1, 1)
      var lenLast = str.substr(str.length - 1)
      //如果第一位是0，第二位不是点，就用数字把点替换掉
      if (str.length > 1 && len1 == 0 && len2 != ".") {
        str = str.substr(1, 1)
      }
      //第一位不能是.
      if (len1 == ".") {
        str = ""
      }
      //最后一位不能是.
      if (str.length == 8 && lenLast == ".") {
        str = ""
      }
      //限制只能输入一个小数点
      if (str.indexOf(".") != -1) {
        var str_ = str.substr(str.indexOf(".") + 1)
        if (str_.indexOf(".") != -1) {
          str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1)
        }
      }
      // //正则替换
      str = str.replace(/[^\d^\.]+/g, '') // 保留数字和小数点
      if (htmlType == 'decimals2') {
        str = str.substr(0, str.indexOf('.') + 3)// 小数点后只能输两位
      }
      this.ItemValChange(str)
      return str
    }
  },
  computed: {
    attributes(){
      //属性对象
      let attrs={
        placeholder: '请输入'+this.itemInfo.columnComment,
        disabled: this.isEdit
      }
      if(this.itemType=='query'){
        /**
         * 查询
         */
        attrs['type']='text'
      }else{
        /**
         * 编辑
         */
        // 多行文本框
        if(this.itemInfo.htmlType=='textarea'){
          attrs['type']='textarea'
          attrs['autosize']={ minRows: 2, maxRows: 6}
        }

        attrs['maxlength']=this.itemInfo.columnLength
        attrs['show-word-limit'] = true
      }
      return attrs;
    },
    // 返回校验规则
    itemRule() {
      let rule = []
      rule.push({
        required: this.isRequired,
        message: this.itemInfo.columnComment + '不能为空',
        trigger: 'blur'
      })
      if (this.itemInfo.htmlType == 'number') {
        rule.push({
          type: 'number',
          message: this.itemInfo.columnComment + '只能为数字'
        })
      }
      return rule;
    },
    // 判断是否显示
    isShow() {
      if (this.itemType == 'edit' || this.itemType == 'add') {
        return this.itemInfo.isInsert == '1'
      } else if (this.itemType == 'query') {
        return this.itemInfo.isQuery == '1'
      } else {
        return false
      }
    },
    //能否编辑
    isEdit() {
      if (this.itemType == 'edit') {
        if (this.disableStatus != undefined && this.disableStatus) return true;
        else return this.itemInfo.isEdit != '1'
      }
      return false
    },
    // 判断是否必填
    isRequired() {
      if (this.itemType == 'edit' || this.itemType == 'add') {
        return this.itemInfo.isRequired == '1'
      } else {
        return false
      }
    },
    compClass() {
      let className = "";
      if (this.inline == false) {
        className = (this.itemType == 'edit' || this.itemType == 'add') ? (this.isFullItem ? 'full-item' : 'half-item') : ''
      } else {
        className = this.isFullItem ? 'full-item' : ''
      }
      return className;
    },
    // 多选下拉框
    multipleSelectFieldData: {
      get: function () {
        if (this.strIsNotEmpty(this.itemInfo.fieldData)) {
          return this.itemInfo.fieldData.split(',')
        } else {
          this.$set(this.itemInfo, 'fieldData', '')
          return this.itemInfo.fieldData;
        }
      },
      set: function (newValue) {
        let key = ''
        if(newValue instanceof Array){
          newValue.forEach(item => {
            key += item + ','
          })
          if (key.trim().length > 0) {
            key = key.substring(0, key.lastIndexOf(','))
          }
        }
        this.itemInfo.fieldData = key
      }
    },
    // 复选框
    checkobxFieldData: {
      get: function () {
        if (this.strIsNotEmpty(this.itemInfo.fieldData)) {
          return this.itemInfo.fieldData.split(',')
        } else {
          return [];
        }
      },
      set: function (newValue) {
        let key = ''
        if(newValue && newValue instanceof Array){
          key = newValue.filter(Boolean).join(",")
        }
        this.$set(this.itemInfo,'fieldData',key)
      }
    }
  },
  watch: {
    itemInfo: {
      immediate: true,
      handler(nowData) {
        if (nowData.htmlType == 'textarea') {
          this.isFullItem = true
        }
        let dictType = nowData.dictType
        if ((nowData.htmlType == 'select' || nowData.htmlType == 'multipleSelect' || nowData.htmlType == 'radio' || nowData.htmlType == 'checkbox') && dictType != '' && dictType != undefined) {
          this.getDicts(dictType).then(response => {
            this.dictList = response.data
          })
        }
      }
    }
  }
}
</script>

<style scoped>
.edit .el-form-item__content .el-input {
  /*width: calc(50%) !important;*/
  min-width: 300px;
  max-width: 500px;
}

.query > .el-form-item__content {
  margin-left: 0px !important;
}
</style>
